package com.hsd.whb.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

public class FreemarkerUtil {


    /**
     * 获取模板
     *
     * @param templateName 模板名称（含后缀名）
     * @return Template
     * @throws IOException
     */
    public static Template getTemplate(String templateName) throws IOException {
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        Template temp = null;
        String tmpRootstr = FreemarkerUtil.class.getResource("/static/" + templateName).getFile();
        File tmpRootFile = new File(tmpRootstr).getParentFile();
        if (tmpRootFile == null) {
            throw new RuntimeException("无法取得模板根路径！");
        }
        try {
            cfg.setDefaultEncoding("utf-8");
            cfg.setOutputEncoding("utf-8");
            cfg.setDirectoryForTemplateLoading(tmpRootFile);
            temp = cfg.getTemplate(templateName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return temp;
    }

    /**
     * 根据freemark模板生成文件
     *
     * @param templateName 模板名称（含后缀名）
     * @param filePath     生成文件路径
     *                     参数
     */
    public static void generateFile(String templateName, String filePath, Object dataMap)
            throws TemplateException, IOException {
        Writer writer = null;
        Template template = getTemplate(templateName);
        String dir = filePath.substring(0, filePath.lastIndexOf(File.separator));
        File fdir = new File(dir);
        if (!fdir.exists()) {
            if (!fdir.mkdirs()) {
                System.out.println("创建目录" + fdir.getAbsolutePath() + "失败");
                return;
            }
        }
        File file = new File(filePath);
        if (file.exists())
            file.delete();
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
        template.setOutputEncoding("utf-8");
        template.process(dataMap, writer);
        writer.flush();
        writer.close();
    }
}
